package com.jiang.jixiang.ui;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.NearbyNearbyMerchantBean;
import com.jiang.jixiang.bean.SellerInfoBean;
import com.jiang.jixiang.bean.SellerListBean;
import com.jiang.jixiang.databinding.ActivitySearchBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.ui.adapter.SearchAdapter;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.ToastUtils;
import com.ws.universal.tools.utils.cache.CacheCacheUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchActivity extends BaseActivity implements NetWorkListener {
    private ActivitySearchBinding binding;
    private SearchAdapter searchAdapter;
    private NearbyNearbyMerchantBean cacheListBeans;
    private List<SellerInfoBean> cacheBeans;

    @Override
    protected void initCreate(Bundle savedInstanceState) {
        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivitySearchBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }


    @Override
    protected void initView() {

        binding.inTitle.titleTextTv.setText(R.string.title_nearby);
        binding.inTitle.titleLeftBtn.setOnClickListener(view -> {
            onBackPressed();
        });
        searchAdapter = new SearchAdapter();

        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rcyData.setLayoutManager(manager);
        binding.rcyData.setAdapter(searchAdapter);


        binding.rlFindMe.setOnClickListener(view -> {
            BaseBusData baseBusData = new BaseBusData(BusCode.find_me);
            EventBusUtil.postEvent(baseBusData);
            onBackPressed();
        });
        LogcatUtils.e(" searchBean " + CacheCacheUtils.getString(Constants.searchBean));
        cacheListBeans = GsonUtils.parseJObject(CacheCacheUtils.getString(Constants.searchBean), NearbyNearbyMerchantBean.class);
        if (cacheListBeans == null) {
            cacheListBeans = new NearbyNearbyMerchantBean();

        }

        if (cacheListBeans.getList() == null) {
            cacheListBeans.setList(new ArrayList<>());
        }
        if (cacheListBeans.getList().size() > 10) {
            cacheListBeans.getList().remove(cacheListBeans.getList().size() - 1);
        }
        searchAdapter.setList(cacheListBeans.getList());
        binding.editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    // 在此处执行搜索操作
                    searchKey = binding.editText.getText().toString().trim();
                    hideSoftInput(binding.editText);
                    showProgressDialog(false);
                    loadData();
                    return true;
                }
                return false;
            }
        });
        binding.editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() == 0) {
                    searchKey = "";
                    if (searchAdapter != null) {
                        searchAdapter.getData().clear();
                        searchAdapter.notifyDataSetChanged();
                    }
                    LogcatUtils.e(" " + cacheListBeans.getList().toString());
                    searchAdapter.setList(cacheListBeans.getList());
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        binding.btnCancel.setOnClickListener(view -> {
            if (searchAdapter != null) {
                searchAdapter.getData().clear();
                searchAdapter.notifyDataSetChanged();
            }
            CacheCacheUtils.put(Constants.searchBean, "");
            cacheListBeans = GsonUtils.parseJObject(CacheCacheUtils.getString(Constants.searchBean), NearbyNearbyMerchantBean.class);
            if (cacheListBeans == null) {
                cacheListBeans = new NearbyNearbyMerchantBean();

            }

            if (cacheListBeans.getList() == null) {
                cacheListBeans.setList(new ArrayList<>());
            }
        });

        searchAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", searchAdapter.getData().get(position).getId());
                pageJump(NearbySellerInfoActivity.class, bundle);
            }
        });

    }

    String searchKey = "";
    private int pageNumber = 1;
    private int pages;

    private void loadData() {
        if (getLocation() != null) {
            Map<String, Object> params = new HashMap<>();
            params.put("longitude", getLocation().getLongitude());
            params.put("latitude", getLocation().getLatitude());
            params.put("isList", "true");
            params.put("page_no", 1);
            params.put("page_size", "20");
            params.put("keyword", searchKey);
            okHttpModel.postJson(ApiUrl.sellerList_Api, params, ApiUrl.sellerList_Api_ID, this);
        }


    }

    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.sellerList_Api_ID:
                NearbyNearbyMerchantBean nearbyNearbyMerchantBean = GsonUtils.parseJObject(data.toString(), NearbyNearbyMerchantBean.class);
                if (nearbyNearbyMerchantBean != null) {
                    if (searchAdapter != null) {
                        searchAdapter.getData().clear();
                        searchAdapter.notifyDataSetChanged();
                    }
                    if (cacheListBeans.getList().size() > 10) {
                        cacheListBeans.getList().remove(cacheListBeans.getList().size() - 1);
                    }
                    if (nearbyNearbyMerchantBean.getList().size() > 0) {


                        if (cacheListBeans.getList().size() > 0) {
                            for (int i = 0; i < nearbyNearbyMerchantBean.getList().size(); i++) {
                                LogcatUtils.e(" indexOf " + nearbyNearbyMerchantBean.getList().get(i).getName().indexOf(searchKey));
                                if (nearbyNearbyMerchantBean.getList().get(i).getName().indexOf(searchKey) > -1) {
                                    cacheListBeans.getList().add(0, new SellerListBean(nearbyNearbyMerchantBean.getList().get(i).getId(),
                                            nearbyNearbyMerchantBean.getList().get(i).getName(),
                                            nearbyNearbyMerchantBean.getList().get(i).getAddress(),
                                            nearbyNearbyMerchantBean.getList().get(i).getLongitude(),
                                            nearbyNearbyMerchantBean.getList().get(i).getLatitude()));
                                    cacheListBeans.removeDuplicate();
                                    try {
                                        JSONObject cacheListBeansGson = new JSONObject(cacheListBeans.toString());
                                        LogcatUtils.e(" cacheListBeans " + cacheListBeansGson);
                                        CacheCacheUtils.put(Constants.searchBean, cacheListBeansGson.toString());
                                    } catch (JSONException e) {
                                        throw new RuntimeException(e);
                                    }


                                }


                            }
                        } else {
                            cacheListBeans.getList().add(new SellerListBean(nearbyNearbyMerchantBean.getList().get(0).getId(),
                                    nearbyNearbyMerchantBean.getList().get(0).getName(),
                                    nearbyNearbyMerchantBean.getList().get(0).getAddress(),
                                    nearbyNearbyMerchantBean.getList().get(0).getLongitude(),
                                    nearbyNearbyMerchantBean.getList().get(0).getLatitude()));
                            try {
                                JSONObject cacheListBeansGson = new JSONObject(cacheListBeans.toString());
                                LogcatUtils.e(" cacheListBeans " + cacheListBeansGson);
                                CacheCacheUtils.put(Constants.searchBean, cacheListBeansGson.toString());
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }

                        }


                    }
                    searchAdapter.setList(nearbyNearbyMerchantBean.getList());
                }
                break;
        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }


    @Override
    protected void FinishDesTroy() {
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }


}
